<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书列表展示</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/list.css">
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script src="js/jq-paginator.js"></script>

</head>

<body>
<div class="bookContainer">
    <h2>图书列表展示</h2>
    <div class="navbar-justify-between">
        <div>
            <button class="btn btn-outline-info" type="button" onclick="location.href='book_add.html'">添加图书</button>
            <button class="btn btn-outline-info" type="button" onclick="batchDelete()">批量删除</button>
        </div>
        <div>
            <button class="btn btn-outline-secondary" type="button" onclick="logout()">退出登录</button>
        </div>
    </div>

    <table>
        <thead>
        <tr>
            <td><input type="checkbox" id="selectAll" onchange="toggleSelectAll()"> 全选</td>
            <td class="width100">图书ID</td>
            <td>书名</td>
            <td>作者</td>
            <td>数量</td>
            <td>定价</td>
            <td>出版社</td>
            <td>状态</td>
            <td class="width200">操作</td>
        </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

    <div class="demo">
        <ul id="pageContainer" class="pagination justify-content-center"></ul>
    </div>
    <script>
        // 检查用户登录状态
        function checkLoginStatus() {
            var isLoggedIn = localStorage.getItem('userLoggedIn');
            var loginTime = localStorage.getItem('loginTime');
            
            // 如果没有登录标识或者登录已超时8小时（可选）
            if (!isLoggedIn || isLoggedIn !== 'true') {
                alert("用户未登录, 请先登录");
                location.href = "login.html";
                return false;
            }
            
            // 可选：检查登录是否超时8小时
            if (loginTime) {
                var currentTime = new Date().getTime();
                var timeDiff = currentTime - parseInt(loginTime);
                var hours = timeDiff / (1000 * 60 * 60);
                
                if (hours > 8) { // 8小时后过期
                    localStorage.removeItem('userLoggedIn');
                    localStorage.removeItem('loginTime');
                    alert("登录已过期，请重新登录");
                    location.href = "login.html";
                    return false;
                }
            }
            
            return true;
        }
        
        // 页面加载时检查登录状态
        if (!checkLoginStatus()) {
            // 如果未登录，停止执行后续代码
        } else {
            getBookList();
        }

        function getBookList() {
            $.ajax({
                type: "get",
                url: "/book/getListByPage" + location.search,
                success: function (result) {

                    if (result == null || result.code =="UNLOGIN") {
                        alert("用户未登录, 请先登录");
                        location.href = "login.html";
                        return;
                    }
                    //其他情况判断, 此处省略
                    if(result == null || result.data == null){
                        return;
                    }
                    var data = result.data;

                    var books = data.records;
                    var finalHtml = "";
                    for (var book of books) {
                        finalHtml += '<tr>';
                        finalHtml += '<td><input type="checkbox" name="selectBook" value="' + book.id + '" id="selectBook" class="book-select" onchange="updateSelectAllStatus()"></td>';
                        finalHtml += '<td>' + book.id + '</td>';
                        finalHtml += '<td>' + book.bookName + '</td>';
                        finalHtml += '<td>' + book.author + '</td>';
                        finalHtml += '<td>' + book.count + '</td>';
                        finalHtml += '<td>' + book.price + '</td>';
                        finalHtml += '<td>' + book.publish + '</td>';
                        finalHtml += '<td>' + book.statusCN + '</td>';
                        finalHtml += '<td><div class="op">';
                        finalHtml += '<a href="book_update.html?bookId=' + book.id + '">修改</a>';
                        finalHtml += '<a href="javascript:void(0)" onclick="deleteBook(' + book.id + ')">删除</a>';
                        finalHtml += '</div></td></tr>';
                    }
                    $("tbody").html(finalHtml);

                    //翻页信息
                    $("#pageContainer").jqPaginator({
                        totalCounts: data.total, //总记录数
                        pageSize: 10,    //每页的个数
                        visiblePages: 5, //可视页数
                        currentPage: data.pageRequest.currentPage,  //当前页码
                        first: '<li class="page-item"><a class="page-link">首页</a></li>',
                        prev: '<li class="page-item"><a class="page-link" href="javascript:void(0);">上一页<\/a><\/li>',
                        next: '<li class="page-item"><a class="page-link" href="javascript:void(0);">下一页<\/a><\/li>',
                        last: '<li class="page-item"><a class="page-link" href="javascript:void(0);">最后一页<\/a><\/li>',
                        page: '<li class="page-item"><a class="page-link" href="javascript:void(0);">{{page}}<\/a><\/li>',
                        //页面初始化和页码点击时都会执行
                        onPageChange: function (page, type) {
                            if (type == "change") {
                                location.href = "book_list.html?currentPage=" + page;
                            }
                        }
                    });
                },
                error: function(error){
                    if(error.status==401){
                        alert("用户未登录, 请先登录");
                        location.href = "login.html";
                    }

                }
            });
        }


        function deleteBook(id) {
            var isDelete = confirm("确认删除?");
            if (isDelete) {
                $.ajax({
                    type: "post",
                    url: "/book/deleteBook?bookId=" + id,
                    success: function (result) {
                        if (result == null || result.code =="UNLOGIN") {
                            alert("用户未登录, 请先登录");
                            location.href = "login.html";
                            return;
                        }
                        
                        if (result.code == "SUCCESS") {
                            alert("删除成功");
                            location.href = "book_list.html?currentPage=1";
                        } else {
                            alert("删除失败：" + (result.errMsg || "未知错误"));
                        }
                    },
                    error: function(xhr, status, error) {
                        if(xhr.status==401){
                            alert("用户未登录, 请先登录");
                            location.href = "login.html";
                        } else {
                            alert("删除请求失败，请重试");
                        }
                    }
                });
            }
        }
        function batchDelete() {
            //获取复选框的id
            var ids = [];
            $("input:checkbox[name='selectBook']:checked").each(function () {
                ids.push($(this).val());
            });
            
            if (ids.length == 0) {
                alert("请选择要删除的图书");
                return;
            }
            
            var isDelete = confirm("确认批量删除这 " + ids.length + " 本图书吗？");
            if (isDelete) {
                console.log(ids);
                $.ajax({
                    type: "post",
                    url: "/book/batchDelete?ids="+ids.join(","),
                    success: function(result){
                        if (result == null || result.code =="UNLOGIN") {
                            alert("用户未登录, 请先登录");
                            location.href = "login.html";
                            return;
                        }
                        
                        if(result.code == "SUCCESS"){
                            alert("批量删除成功");
                            location.href = "book_list.html?currentPage=1";
                        }else{
                            alert("批量删除失败：" + (result.errMsg || "未知错误"));
                        }
                    },
                    error: function(xhr, status, error) {
                        if(xhr.status==401){
                            alert("用户未登录, 请先登录");
                            location.href = "login.html";
                        } else {
                            alert("批量删除请求失败，请重试");
                        }
                    }
                });
            }
        }

        // 全选/反选功能
        function toggleSelectAll() {
            var selectAll = $("#selectAll").prop("checked");
            $("input[name='selectBook']").prop("checked", selectAll);
        }

        // 监听单个复选框状态，更新全选按钮状态
        function updateSelectAllStatus() {
            var totalCheckboxes = $("input[name='selectBook']").length;
            var checkedCheckboxes = $("input[name='selectBook']:checked").length;
            $("#selectAll").prop("checked", totalCheckboxes > 0 && checkedCheckboxes === totalCheckboxes);
        }
        
        // 退出登录
        function logout() {
            var confirmLogout = confirm("确认退出登录吗？");
            if (confirmLogout) {
                // 清除localStorage中的登录信息
                localStorage.removeItem('userLoggedIn');
                localStorage.removeItem('loginTime');
                // 跳转到登录页面
                location.href = "login.html";
            }
        }

    </script>
</div>
</body>

</html>